#import "FlutterKstPlugin.h"
#import <KsIMSDK/KsIMSDK.h>

@implementation FlutterKstPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel* channel = [FlutterMethodChannel
                                     methodChannelWithName:@"flutter_kst_plugin"
                                     binaryMessenger:[registrar messenger]];
    FlutterKstPlugin* instance = [[FlutterKstPlugin alloc] init];
    [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    if ([@"getPlatformVersion" isEqualToString:call.method]) {
        result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
    }if ([@"initKST" isEqualToString:call.method]){
        NSDictionary* argsMap=call.arguments;
        NSString * key= argsMap[@"key"];
        NSString * compId= argsMap[@"compId"];
        [self initKST:key compId:compId result:result];
        
    }else if ([@"openKST" isEqualToString:call.method]) {
        [self openKST];
    }else if ([@"closeKST" isEqualToString:call.method]) {
             [self closeKST];
         } else {
        result(FlutterMethodNotImplemented);
    }
}


- (void)initKST:(NSString *)key compId:(NSString *)compId result:(FlutterResult)result{
    
    [[KsClient sharedInstance] initSdk:key
                                compId:compId
                              response:^(KsResponse *response) {
        NSString *status = response.status;
        if([@"success" isEqualToString:status]){
            result(@"true");
        }else{
            result(@"false");
        }
    }];
}
- (void)openKST{
    
    //初始化成功
    if (![KsClient sharedInstance].isOpen) {
        [[KsClient sharedInstance] openConversation];
    }
    FlutterViewController *controller = (FlutterViewController *)[UIApplication sharedApplication].keyWindow.rootViewController;
    [[KsClient sharedInstance] pushChatViewOnViewController:controller];
    
}

- (void)closeKST{
  if ([KsClient sharedInstance].isOpen) {
   [[KsClient sharedInstance] closeSession];
   }
}
@end
